package boot

import (
	"fmt"

	"yunj/app/corn/config"
	"yunj/pkg/global"
	yunjCornConfig "yunj/pkg/yunj/app/corn/config"
	"yunj/pkg/yunj/app/model"
	"yunj/pkg/yunj/core/corn"
	"yunj/pkg/yunj/core/log"

	"github.com/robfig/cron/v3"
)

// 初始化定时任务
func InitCorn() {
	tasks := append(config.Tasks, yunjCornConfig.Tasks...)
	// 获取数据库状态值
	var items []*model.Corn
	err := global.MySQL.Find(&items).Error
	if err != nil {
		panic(fmt.Sprintf("获取定时任务失败: %v", err))
	}
	itemsMap := make(map[string]*model.Corn)
	for _, item := range items {
		itemsMap[item.Name] = item
	}
	for _, t := range tasks {
		if item, exists := itemsMap[t.Name()]; exists {
			err = t.SetHandleStatus(item.Status)
		} else {
			err = t.SetHandleStatus(t.DefaultHandleStatus())
		}
		if err != nil {
			panic(fmt.Sprintf("%s状态设置异常: %v", t.LogPrefix(), err))
		}
	}
	global.Corn = cron.New(cron.WithSeconds())
	err = corn.TaskScheduler.Start(tasks)
	if err != nil {
		panic(fmt.Sprintf("定时任务执行失败: %v", err))
	}
	// 启动cron调度器
	global.Corn.Start()
	log.Info("定时任务执行开始...")
}
